package com.cqupt.scanning.system.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqupt.scanning.handler.exception.MyException;
import com.cqupt.scanning.system.acl.entity.AclRole;
import com.cqupt.scanning.system.acl.entity.AclRoleGroup;
import com.cqupt.scanning.system.acl.entity.AclRolePermission;
import com.cqupt.scanning.system.acl.entity.vo.RoleVO;
import com.cqupt.scanning.system.acl.mapper.AclRoleMapper;
import com.cqupt.scanning.system.acl.service.AclRoleGroupService;
import com.cqupt.scanning.system.acl.service.AclRolePermissionService;
import com.cqupt.scanning.system.acl.service.AclRoleService;
import com.cqupt.scanning.system.utils.result.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 宋宝梁
 * @since 2021-07-05
 */
@Service
public class AclRoleServiceImpl extends ServiceImpl<AclRoleMapper, AclRole> implements AclRoleService {

    @Autowired
    private AclRoleGroupService aclRoleGroupService;

    @Autowired
    private AclRolePermissionService aclRolePermissionService;

    @Override
    public List<String> selectRoleByUserId(Integer userId) {
        return baseMapper.selectRoleByUserId(userId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public R addRole(RoleVO roleVO) {
        try {
            Integer count = baseMapper.selectCount(new QueryWrapper<AclRole>().eq("role_name", roleVO.getRoleName()));
            if (count >= 1) R.error().message("角色名已被使用！");

            AclRole aclRole = new AclRole();
            AclRoleGroup aclRoleGroup = aclRoleGroupService.getOne(new QueryWrapper<AclRoleGroup>().eq("role_group_name", roleVO.getRoleGroupName()));
            aclRole.setRoleName(roleVO.getRoleName().trim())
                    .setRoleGroupId(aclRoleGroup.getId())
                    .setRemark(roleVO.getRemark());
            baseMapper.insert(aclRole);

            List<AclRolePermission> rolePermissionList = new ArrayList<>();
            Integer[] permissionIds = roleVO.getPermissionIds();
            for (Integer permissionId : permissionIds) {
                AclRolePermission aclRolePermission = new AclRolePermission();
                aclRolePermission.setRoleId(aclRole.getId())
                        .setPermissionId(permissionId);
                rolePermissionList.add(aclRolePermission);
            }
            aclRolePermissionService.saveBatch(rolePermissionList, rolePermissionList.size());
            return R.ok();
        } catch (Exception e) {
            e.getStackTrace();
            throw new MyException(20001, "角色添加失败！");
        }
    }

    @Override
    public R getOneRole(Integer roleId) {
        AclRole role = baseMapper.selectById(roleId);
        RoleVO roleVO = new RoleVO();
        BeanUtils.copyProperties(role, roleVO);
        return R.ok().data("role", roleVO);
    }

    @Override
    public R getAllRole(Page<AclRole> page, String query) {
        IPage<AclRole> roles = baseMapper.selectPage(page, new QueryWrapper<AclRole>().like("role_name", query));
        List<AclRole> records = roles.getRecords();
        List<RoleVO> roleList = new ArrayList<>();
        for (AclRole record : records) {
            RoleVO roleVO = new RoleVO();
            BeanUtils.copyProperties(record, roleVO);
            roleList.add(roleVO);
        }
        return R.ok().data("roleList", roleList).data("total", roles.getTotal());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public R updateRole(RoleVO roleVO) {
        try {
            AclRole aclRole = new AclRole();
            AclRoleGroup roleGroup = aclRoleGroupService.getOne(new QueryWrapper<AclRoleGroup>().eq("role_group_name", roleVO.getRoleGroupName()));
            aclRole.setRemark(roleVO.getRoleName().trim())
                    .setRoleGroupId(roleGroup.getId())
                    .setRemark(roleVO.getRemark())
                    .setId(roleVO.getId())
                    .setDownloadNum(roleVO.getDownloadNum())
                    .setVersion(roleVO.getVersion())
                    .setRoleName(roleVO.getRoleName());
            baseMapper.updateById(aclRole);

            aclRolePermissionService.remove(new QueryWrapper<AclRolePermission>().eq("role_id", aclRole.getId())); // 删除原有的角色-权限关系

            List<AclRolePermission> rolePermissionList = new ArrayList<>();
            Integer[] permissionIds = roleVO.getPermissionIds();
            for (Integer permissionId : permissionIds) {
                AclRolePermission aclRolePermission = new AclRolePermission();
                aclRolePermission.setRoleId(aclRole.getId())
                        .setPermissionId(permissionId);
                rolePermissionList.add(aclRolePermission);
            }
            aclRolePermissionService.saveBatch(rolePermissionList, rolePermissionList.size());
            return R.ok();
        } catch (Exception e) {
            e.getStackTrace();
            throw new MyException(20001, "修改失败，请重新尝试!");
        }

    }

    @Override
    public R removeRoleById(Integer roleId) {
        int id = baseMapper.deleteById(roleId);
        if (id <= 0) return R.error().message("Fail to delete");
        return R.ok();
    }
}
